/*
 * @Description: 城际出行输入位置 LocationSearchPage
 * @version: 
 * @Company: 
 * @Author: ZhengZhuang
 * @Date: 2019-09-16 14:34:08
 * @LastAuthor   : zhengzhuang
 * @lastTime     : 2020-01-18 14:36:27
 */
import 'dart:convert';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:C20Driver/model/user_realtime_location_model.dart';
import 'package:C20Driver/provider/position_information.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:provider/provider.dart';

class LocationSearchPage extends StatefulWidget {
  @override
  _LocationSearchPageState createState() => _LocationSearchPageState();
}

class _LocationSearchPageState extends State<LocationSearchPage> {
  List<String> _result = [];
  String _driverCurrentCity = "青岛市";
  TextEditingController _inputController;
  String _inputTxt = "";
  @override
  void initState() {
    super.initState();
    _setCity();
  }

  _setCity() async {
    setState(() {
      _driverCurrentCity =
          Provider.of<PositionInformation>(context, listen: false)
              .driverCurrentCity;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        child: AppBar(
          brightness: Brightness.light,
          backgroundColor: Colors.white,
          automaticallyImplyLeading: false,
          title: _headTopInputSearch(),
          actions: <Widget>[
            InkWell(
              child: Container(
                width: ScreenUtil().setWidth(100.0),
                height: ScreenUtil().setWidth(100.0),
                alignment: Alignment.center,
                child: Text(
                  '取消',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(30.0),
                    color: Colors.black54,
                  ),
                ),
              ),
              onTap: () => NavigatorUtil.goBack(context),
            ),
          ],
          elevation: 0.0,
        ),
        preferredSize: Size.fromHeight(ScreenUtil().setWidth(100.0)),
      ),
      resizeToAvoidBottomPadding: false, //输入框抵住键盘
      body: _searchList(),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _inputController.dispose();
  }

  /// 顶部搜索输入框
  Widget _headTopInputSearch() {
    return Container(
      width: ScreenUtil().setWidth(750.0),
      height: ScreenUtil().setWidth(100.0),
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          _currentCity(),
          Container(
            width: ScreenUtil().setWidth(1.0),
            height: ScreenUtil().setWidth(50.0),
            color: Colors.black12,
          ),
          SizedBox(width: ScreenUtil().setWidth(5.0)),
          _inputBoardingPoint(),
        ],
      ),
    );
  }

  // 当前城市
  Widget _currentCity() {
    return InkWell(
      child: Container(
        width: ScreenUtil().setWidth(160.0),
        height: ScreenUtil().setWidth(100.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              width: ScreenUtil().setWidth(100.0),
              alignment: Alignment.center,
              child: Text(
                '$_driverCurrentCity',
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(30.0),
                  color: Colors.black54,
                ),
              ),
            ),
            Icon(Icons.arrow_drop_down,
                size: ScreenUtil().setWidth(60.0), color: Colors.black26),
          ],
        ),
      ),
      onTap: () =>
          NavigatorUtil.jump(context, '/urbanChoice').then((value) async {
        if (value != null) {
          setState(() {
            _driverCurrentCity = value;
          });
          final poiList =
              await AmapSearch.searchKeyword(_inputTxt, city: value);
          Stream.fromIterable(poiList)
              .asyncMap((it) async =>
                  '{"title": "' +
                  (await it.title) +
                  '", "address": "' +
                  (await it.address) +
                  '", "businessArea": "' +
                  (await it.address) +
                  '", "cityName": "' +
                  (await it.cityName) +
                  '", "adName": "' +
                  (await it.adName) +
                  '", "lat": "' +
                  ((await it.latLng).latitude).toString() +
                  '", "lon": "' +
                  ((await it.latLng).longitude).toString() +
                  '"}')
              .toList()
              .then(
                (it) => setState(() {
                  _result = it;
                }),
              );
        }
      }),
    );
  }

  // 输入上车点
  Widget _inputBoardingPoint() {
    return Container(
      width: ScreenUtil().setWidth(350.0),
      height: ScreenUtil().setWidth(100.0),
      child: TextField(
        controller: _inputController,
        autofocus: true,
        decoration: InputDecoration(
          hintText: '请输入您想要选择的位置',
          hintStyle: TextStyle(
            fontSize: ScreenUtil().setSp(30.0),
            color: Colors.black38,
          ),
          border: InputBorder.none,
        ),
        onChanged: (e) async {
          /// 搜索关键字poi
          _inputTxt = e;
          final poiList =
              await AmapSearch.searchKeyword(e, city: _driverCurrentCity);
          Stream.fromIterable(poiList)
              .asyncMap((it) async =>
                  '{"title": "' +
                  (await it.title) +
                  '", "address": "' +
                  (await it.address) +
                  '", "businessArea": "' +
                  (await it.address) +
                  '", "cityName": "' +
                  (await it.cityName) +
                  '", "adName": "' +
                  (await it.adName) +
                  '", "lat": "' +
                  ((await it.latLng).latitude).toString() +
                  '", "lon": "' +
                  ((await it.latLng).longitude).toString() +
                  '"}')
              .toList()
              .then((it) => setState(() => _result = it));
        },
      ),
    );
  }

  // 搜索结果页
  Widget _searchList() {
    if (_result.length != 0) {
      return Container(
        color: Colors.white,
        child: ListView(
            children: _result.map((item) {
          return _searchEndOneList(item);
        }).toList()),
      );
    } else {
      return Text('');
    }
  }

  // 搜索结果单个列表
  Widget _searchEndOneList(item) {
    var dataItem = json.decode(item);
    return InkWell(
      child: Container(
        padding: EdgeInsets.only(left: ScreenUtil().setWidth(30.0)),
        child: Column(
          children: <Widget>[
            ListTile(
              leading: Image.asset(
                'assets/icon/icon_linear_dingwei.png',
                width: ScreenUtil().setWidth(48),
                height: ScreenUtil().setWidth(48),
              ),
              title: Text(
                dataItem['title'],
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(30.0),
                ),
              ),
              subtitle: Text(
                dataItem['address'],
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(26.0),
                  color: Colors.black38,
                ),
              ),
            ),
            Divider(height: ScreenUtil().setWidth(1.0)),
          ],
        ),
      ),
      onTap: () {
        UserRealtimeLocationModel localData =
            UserRealtimeLocationModel.fromJson({
          "name": dataItem['title'],
          "cityName": dataItem['cityName'],
          "lat": double.parse(dataItem['lat']),
          "lng": double.parse(dataItem['lon']),
        });
        NavigatorUtil.goBackWithParams(context, localData);
      },
    );
  }
}
